package com.seminario.spring.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.seminario.spring.form.RegistrationForm;
import com.seminario.spring.manager.UserManager;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	@Autowired
	private UserManager userManager;
	

	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);

	/**
	 * Simply selects the home view to render by returning its name.
	 */

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(HttpServletRequest request) {
		logger.info("Welcome home!");
		return "home";
	}

	@RequestMapping(value = "load", method = RequestMethod.GET)
	public ModelAndView load(HttpServletRequest request) {
		logger.info("load");
		return new ModelAndView("content");
	}
	
	@RequestMapping(value = "gotoRegistrarUsuario")
	public ModelAndView gotoRegistrarUsuario() {

		return new ModelAndView("registrarUsuario");
	}
	@RequestMapping(value = "registrarUsuario", method = RequestMethod.POST)
	public ModelAndView registrarUsuario(@Valid RegistrationForm registerForm,
			BindingResult result, Map<String, Object> model,
			HttpServletRequest request) {
		try {
			userManager.saveUser(registerForm);
		} catch (Exception e) {
		}
		return new ModelAndView("content");
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(@Valid RegistrationForm registerForm,
			BindingResult result, Map<String, Object> model,
			HttpServletRequest request) {
		boolean validateUser = false;
		try {
			validateUser = userManager.validateUser(registerForm.getEmail(),
					registerForm.getPassword(),request.getSession());
		} catch (Exception e) {
		}
		if (validateUser) {
			return "redirect:/caralibro/getAmigos";	//new ModelAndView("caralibro/inicio");
		} else {
			return "home";//new ModelAndView("content");
		}
	}
	
}
